package com.create404.suishoupai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.create404.suishoupai.dto.EmployeeDto;
import com.create404.suishoupai.entity.Employee;
import com.create404.suishoupai.mapper.EmployeeMapper;
import com.create404.suishoupai.service.IEmployeeService;
import com.create404.suishoupai.utils.SaltUtil;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author create404
 * @since 2021-07-17
 */
@Service("employeeService")
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void insert(Employee employee) {
        employeeMapper.insert(employee);
    }

    @Override
    public List<Employee> selectAll() {
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name","avatar");
        return employeeMapper.selectList(wrapper);
    }

    @Override
    public Employee findRolesByEmployeeId(String employeeId) {
        return employeeMapper.findRolesByEmployeeId(employeeId);
    }

    @Override
    public void register(Employee employee) {

        //处理业务调用dao
        //明文密码进行md5 + salt + hash散列
        //1.生成随机盐
        String salt = SaltUtil.getSalt(8);
        //2.将随机盐保存到数据
        employee.setSalt(salt);
        Md5Hash md5Hash = new Md5Hash(employee.getPassword(), salt, 1024);
        employee.setPassword(md5Hash.toHex());

        employeeMapper.insert(employee);
    }

    @Override
    public Map<String, List<EmployeeDto>> selectEDo() {
        List<EmployeeDto> lists = employeeMapper.selectDe();
        Map<String, List<EmployeeDto>> resultMap = new HashMap<String, List<EmployeeDto>>();
        for (EmployeeDto employeeDto : lists) {
            String deId = employeeDto.getDepartmentId();
            if (resultMap.keySet().contains(deId)) {
                resultMap.get(deId).add(employeeDto);
            } else {
                List<EmployeeDto> tempServerList = new ArrayList<>();
                tempServerList.add(employeeDto);
                resultMap.put(deId, tempServerList);
            }
        }
        return resultMap;
    }

    @Override
    public boolean updateByPhone(Employee employee) {
        return employeeMapper.updateByPhone(employee);
    }
}
